package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.CoinHistoryListAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.CoinHistoryListObject;
import com.iexbuy.ihg.entity.CoinHistoryListObjectResponce;
import com.iexbuy.ihg.entity.UserProfile;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WeDeCoinRecordsFragment extends BaseFragment {

	private static WeDeCoinRecordsFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;
	@ViewInject(R.id.coinBalance)
	private TextView coinBalance;

	private List<CoinHistoryListObject> coinHistoryListObjects = new ArrayList<CoinHistoryListObject>();
	private int pageNo = 0;
	private CoinHistoryListAdapter coinHistoryListAdapter;
	private static String areaCode;
	private static int coinArea;
	private RelativeLayout listHeaderView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_wede_coin_records, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		if (areaCode!=null){
			mBaseActivity.setTitle(getResources().getString(R.string.we_de_special_coins));
		}else {
			mBaseActivity.setTitle(getResources().getString(R.string.we_de_coins));
		}

		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		listHeaderView = (RelativeLayout) mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_wede_coin_records_header, null);
		ViewUtils.inject(this, listHeaderView);
		listView.addHeaderView(listHeaderView);

		msgListRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				initCoinRecordsData();
				initMyProfileData();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				loadMore();
			}
		});
	}

	public void onResume() {
		super.onResume();
		msgListRefreshLayout.autoRefresh();
	}

	private void loadMore() {
		pageNo ++;
		initCoinRecordsData();
	}
	@Override
	public void onPause() {
		super.onPause();
		areaCode=null;
		coinArea=-1;
	}

	public void initCoinRecordsData() {

		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userId", App.sPreferences.getUserId());
		if (areaCode!=null){
			paramMap.put("areaCode", areaCode);
			Log.d("aa", areaCode);
			Log.d("aa",App.sPreferences.getUserId());

		}
		paramMap.put("pageNo", String.valueOf(pageNo));
		paramMap.put("pageSize", String.valueOf(ExtraKeyConstant.COMMON_PAGE_SIZE));
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_COIN_HISTORY, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESHING);
					}

					@Override
					public void onCancelled() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.DONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
						CoinHistoryListObjectResponce rep = JsonUtils.parseJsonStrToObject(responseInfo.result, CoinHistoryListObjectResponce.class);
						if (pageNo == 0) {
							coinHistoryListObjects.clear();
						}
						coinHistoryListObjects.addAll(rep.getBody());
						initListView();

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
					}
				});
	}

	private void initListView() {
		if (coinHistoryListAdapter == null) {
			coinHistoryListAdapter = new CoinHistoryListAdapter(mBaseActivity, coinHistoryListObjects);
			listView.setAdapter(coinHistoryListAdapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
					WeDeCoinRecordDetailFragment.setCoinHistoryListObject(coinHistoryListObjects.get(i));
					CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeCoinRecordDetailFragment.class);
				}
			});
		}
		coinHistoryListAdapter.notifyDataSetChanged();
	}

	private void initMyProfileData() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userId", App.sPreferences.getUserId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_MY_PROFILE, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						UserProfile profile = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), UserProfile.class);
						App.sPreferences.setCoinBalance(String.valueOf(profile.getCoinBalance()));
						App.sPreferences.setCashBalance(String.valueOf(profile.getCashBalance()));

						initCoinBalance();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void initCoinBalance() {
		if (coinArea!=-1){
			coinBalance.setText(String.valueOf(coinArea));
		}else {
			coinBalance.setText(App.sPreferences.getCoinBalance());
		}

	}
	public static void setAreaCode(String areaCode) {
		WeDeCoinRecordsFragment.areaCode = areaCode;
	}
	public static void setCoinArea(int coinArea) {
		WeDeCoinRecordsFragment.coinArea = coinArea;
	}
	@OnClick(R.id.buyCoinBtn)
	public void buyCoinBtnClick(View view) {
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeCoinBuyingFragment.class);
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static WeDeCoinRecordsFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
